//
//  BottomScrollView.m
//  scroll嵌套Table+悬停效果
//
//  Created by chenleping on 2018/6/21.
//  Copyright © 2018年 IAPTest. All rights reserved.
//

#import "BottomScrollView.h"


@interface BottomScrollView()<UITableViewDelegate, UITableViewDataSource>
{
    BOOL canMove;
}

@property (nonatomic, strong) NSMutableArray *viewArrs;
@end

@implementation BottomScrollView

- (instancetype)initWithFrame:(CGRect)frame{
    self = [super initWithFrame:frame];
    if (self) {
        self.viewArrs = [NSMutableArray array];
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(canMove) name:@"contentCanMove" object:nil];
        [self setUpChildControl];
        canMove = NO;
    }
    return self;
}

-(void)layoutSubviews {
    self.contentSize = CGSizeMake(self.viewArrs.count * self.bounds.size.width, self.bounds.size.height);
    [self.viewArrs enumerateObjectsUsingBlock:^(UIView *  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        obj.frame = CGRectMake(idx * self.bounds.size.width, 0, self.bounds.size.width, self.bounds.size.height - 30);
    }];
}

- (void)canMove{
    canMove = YES;
}

- (void)scrollViewDidScroll:(UIScrollView *)scrollView{
    if(canMove == NO){
        [scrollView setContentOffset:CGPointMake(0, 0)];
    }
    CGFloat offsetY = scrollView.contentOffset.y;
    if (offsetY <= 0) {
        [[NSNotificationCenter defaultCenter] postNotificationName:@"OtherCanMove" object:nil];
        canMove = NO;
    }
}

- (void)setUpChildControl{
    self.backgroundColor = [UIColor yellowColor];
    self.pagingEnabled = YES;
    for (NSInteger i = 0; i < 3; i ++) {
        UITableView * tableView = [[UITableView alloc] init];
        [self addSubview:tableView];
        tableView.delegate = self;
        tableView.dataSource = self;
        tableView.backgroundColor = [UIColor blueColor];
        [self.viewArrs addObject:tableView];
    }
}

-(void)scrollToPage:(NSInteger)page {
    [self setContentOffset:CGPointMake(self.bounds.size.width * page, 0) animated:YES];
}


#pragma mark --- UITableViewDataSource
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return 40;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    static NSString * cellid = @"cellid";
    UITableViewCell * cell = [tableView dequeueReusableCellWithIdentifier:cellid];
    if (cell == nil) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellid];
    }
    NSString * str = [NSString stringWithFormat:@"%lu", indexPath.row];
    cell.textLabel.text = [NSString stringWithFormat:@"我是中国人%@", str];
    return cell;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    if (self.didSelectedBlock) {
        self.didSelectedBlock();
    }
}
@end
